const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get()

    if (query.name) {
      query.name = ['like', `%${query.name}%`]
    }

    delete query.page
    delete query.size

    const model = this.model('tags');
    const data = await model.where(query).order(['id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

  async allAction() {

    const model = this.model('tags');
    const data = await model.order(['id DESC']).select()
    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('tags');

    if (id > 0) {
      await model.where({id: id}).update(values);
    } else {
      delete values.id;

      const hasUser = await model.where({name: values.name}).find()
      if(!think.isEmpty(hasUser)){
        return this.fail(400, '名称已存在');
      }
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()']

      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('tags').where({id: id}).limit(1).delete();

    return this.success();
  }

  async checkTagNumAction(){
    const tags = await this.model('tags').select()
    for (const item of tags) {
      const count = await this.model('figure').where({tag: ['like', '%'+item.id+'%']}).count()
      await this.model('tags').where({id: item.id}).update({
        count: count
      })
    }

    return this.success();
    
  }
};
